import React, { Fragment } from "react";
import { Menu } from "antd";
import {
  AppstoreOutlined,
  PieChartOutlined,
  DesktopOutlined,
  ContainerOutlined,
  MailOutlined,
} from "@ant-design/icons";
import { connect } from "dva";
import { Link } from "umi";
import storage from "@/utils/storage";

const getExpandArray = (original) => {
  let resultArray = [];
  try {
    const strList = storage.get("$expand");
    resultArray = strList.concat(original);
  } catch {
    resultArray = [...original];
  }
  return [...new Set(resultArray)];
};

const makeMenu = (extra, pathname) => {
  let level = 0;
  let currentPath = [];
  let selectedTitle = "";
  const recursiveMenus = (
    menus,
    parent = { key: "" },
    stack = [],
    isTopLevel = true
  ) => {
    const parentKey = parent.key;
    if (!isTopLevel) level += 1;
    return menus.map((menu, key) => {
      const { title, path, routes } = menu;
      stack.push({ key: true, ...menu });

      if (isTopLevel) level = 0;
      if (!selectedTitle && path === pathname) selectedTitle = title;
      if (!selectedTitle && routes?.length) currentPath[level] = menu.title;

      if (routes?.length) {
        return (
          <Menu.SubMenu
            key={title}
            title={title}
            icon={parentKey ? null : <AppstoreOutlined />}
          >
            {recursiveMenus(routes, { key }, stack, false)}
          </Menu.SubMenu>
        );
      } else {
        return !menu.hiddenInMenu ? (
          <Menu.Item key={title} icon={parentKey ? null : <AppstoreOutlined />}>
            <Link to={path}>{title}</Link>
          </Menu.Item>
        ) : null;
      }
    });
  };
  const menu = recursiveMenus(extra, pathname);
  return { currentPath, selectedTitle, menu: menu.filter((v) => v) };
};

const AppMenu = (props) => {
  const { routes, $app, router } = props;
  const { menuCollapsed } = $app;
  const extra = routes.find((r) => r.menu).routes;

  const { menu, currentPath, selectedTitle } = makeMenu(
    extra,
    router.location.pathname
  );
  const defaultOpenKeys = getExpandArray(currentPath);

  const onOpenChanged = (item) => {
    storage.set("$expand", item);
  };
  return (
    <Fragment>
      <div>LOGO</div>
      <Menu
        defaultSelectedKeys={[selectedTitle]}
        defaultOpenKeys={defaultOpenKeys}
        mode="inline"
        theme="dark"
        inlineCollapsed={menuCollapsed}
        triggerSubMenuAction="click"
        onOpenChange={onOpenChanged}
      >
        {menu}
      </Menu>
    </Fragment>
  );
};

export default connect((m) => m)(AppMenu);
